package com.example.myapplication

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.myapplication.adapter.StockAdapter
import com.example.myapplication.config.AppConfig
import com.example.myapplication.databinding.ActivityMainBinding
import com.example.myapplication.utils.PushNotificationHelper
import com.example.myapplication.viewmodel.StockViewModel

class MainActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityMainBinding
    private val viewModel: StockViewModel by viewModels()
    private lateinit var stockAdapter: StockAdapter
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 初始化AppConfig
        AppConfig.init(this)
        
        // 初始化推送服务
        initializePushNotification()
        
        setupUI()
        setupObservers()
        
        // 加载股票列表
        viewModel.loadPopularStocks()
        
        // 处理推送通知点击事件
        handlePushNotificationIntent(intent)
    }
    
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        handlePushNotificationIntent(intent)
    }
    
    /**
     * 初始化推送通知服务
     */
    private fun initializePushNotification() {
        // 初始化FCM并注册token到后端
        PushNotificationHelper.initialize(this)
        android.util.Log.d("MainActivity", "📱 推送服务已初始化")
    }
    
    /**
     * 处理推送通知点击事件
     */
    private fun handlePushNotificationIntent(intent: Intent?) {
        intent?.let {
            val action = it.getStringExtra("action")
            val stockSymbol = it.getStringExtra("stock_symbol")
            
            android.util.Log.d("MainActivity", "📬 处理推送通知: action=$action, symbol=$stockSymbol")
            
            if (action == "open_detail" && !stockSymbol.isNullOrEmpty()) {
                // 从推送通知中获取股票代码，打开详情页
                val detailIntent = Intent(this, StockDetailActivity::class.java).apply {
                    putExtra("STOCK_SYMBOL", stockSymbol)
                }
                startActivity(detailIntent)
            }
        }
    }
    
    private fun setupUI() {
        // 设置Toolbar菜单
        binding.toolbar.apply {
            inflateMenu(R.menu.main_menu)
            setOnMenuItemClickListener { menuItem ->
                when (menuItem.itemId) {
                    R.id.action_settings -> {
                        // 打开设置界面
                        val intent = Intent(this@MainActivity, SettingsActivity::class.java)
                        startActivity(intent)
                        true
                    }
                    else -> false
                }
            }
        }
        
        // 设置RecyclerView
        stockAdapter = StockAdapter { stock ->
            // 点击股票项，跳转到详情页
            val intent = Intent(this, StockDetailActivity::class.java).apply {
                putExtra("STOCK_SYMBOL", stock.symbol)
                putExtra("STOCK_NAME", stock.name)
            }
            startActivity(intent)
        }
        
        binding.stocksRecyclerView.apply {
            adapter = stockAdapter
            layoutManager = LinearLayoutManager(this@MainActivity)
            addItemDecoration(DividerItemDecoration(this@MainActivity, DividerItemDecoration.VERTICAL))
        }
        
        // 设置下拉刷新
        binding.swipeRefreshLayout.apply {
            setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light
            )
            setOnRefreshListener {
                refreshStocks()
            }
        }
        
        // 设置搜索框
        binding.searchEditText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            
            override fun afterTextChanged(s: Editable?) {
                val query = s?.toString() ?: ""
                viewModel.searchStocks(query)
            }
        })
    }
    
    /**
     * 刷新股票列表
     */
    private fun refreshStocks() {
        val query = binding.searchEditText.text?.toString() ?: ""
        if (query.isEmpty()) {
            // 如果没有搜索内容，刷新热门股票
            viewModel.refreshPopularStocks()
        } else {
            // 如果有搜索内容，重新搜索
            viewModel.searchStocks(query)
        }
    }
    
    private fun setupObservers() {
        // 观察股票列表
        viewModel.stocks.observe(this) { stocks ->
            stockAdapter.submitList(stocks)
            binding.emptyTextView.visibility = if (stocks.isEmpty()) View.VISIBLE else View.GONE
        }
        
        // 观察加载状态
        viewModel.isLoading.observe(this) { isLoading ->
            binding.progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
            // 停止下拉刷新动画
            if (!isLoading && binding.swipeRefreshLayout.isRefreshing) {
                binding.swipeRefreshLayout.isRefreshing = false
            }
        }
        
        // 观察错误信息
        viewModel.error.observe(this) { error ->
            error?.let {
                Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
                viewModel.clearError()
            }
        }
    }
}

